import sys
from selenium import webdriver
from Common.plugs.get_config import r_config
import pytest
import os
import allure
from selenium.webdriver.chrome.options import Options
from Common.plugs.get_log import logger

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
if sys.platform == "win32":
    conf_dir = os.path.join(BASE_DIR, 'Common/config/config.ini').replace('/', '\\')
    driver_dir = r_config(conf_dir, "driver", "dirver_path")
else:
    conf_dir = os.path.join(BASE_DIR, 'Common/config/config.ini')
    driver_dir = r_config(conf_dir, "driver", "dirver_path_linux")

driver = None
browser_options = Options()
# browser_options.add_argument("--headless")
browser_options.add_argument("--disable-gpu")
browser_options.add_argument("--no-sandbox")
browser_options.add_argument("--lang=zh-CN")
browser_options.add_argument('--window-size=1920,1080')
browser_options.add_argument(
    'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"')
browser_options.add_argument('accept-language="zh-cn,zh;q=0.5"')


@pytest.fixture(scope='session')
def project_session_start():
    logger.info("==========开始 XX项目 执行测试===========")
    global driver
    driver = webdriver.Chrome(executable_path=driver_dir, chrome_options=browser_options)
    driver.implicitly_wait(8)
    driver.maximize_window()
    yield driver
    driver.quit()
    logger.info("==========结束 XX项目 测试===========")


@pytest.fixture(scope='module')
def project_module_start():
    logger.info("==========开始 XX模块 执行测试===========")
    global driver
    driver = webdriver.Chrome(executable_path=driver_dir, options=browser_options)
    driver.implicitly_wait(8)
    driver.maximize_window()
    yield driver
    driver.quit()
    logger.info("==========结束 XX模块 测试===========")


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取每个用例状态的钩子函数
    :param item:
    :param call:
    :return:
    """
    # 获取钩子方法的调用结果
    outcome = yield
    rep = outcome.get_result()
    # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        # 添加allure报告截图
        if hasattr(driver, "get_screenshot_as_png"):
            with allure.step('添加失败截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
        # 加入失败后页面刷新不影响后续用例操作
        if hasattr(driver, "refresh"):
            driver.refresh()
